package com.hmall.controller.back;

import com.hdmall.business.common.annotation.AuthRequired;
import com.hdmall.business.common.common.ServerResponse;
import com.hmall.mapper.MallAuctionApplyMapper;
import com.hmall.mapper.MallAuctionItemDetailMapper;
import com.hmall.mapper.MallAuctionItemMapper;
import com.hmall.mapper.MallAuctionMapper;
import com.hmall.model.MallAuction;
import com.hmall.model.MallAuctionApply;
import com.hmall.model.MallAuctionItem;
import com.hmall.model.MallAuctionItemDetail;
import com.hdmall.business.common.util.HttpClientUtil;
import com.hdmall.business.common.util.NumberUtil;
import com.hmall.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/manage/auction")
@Api(value = "后台竞拍管理操作API", description = "后台竞拍管理类API说明")
public class AuctionManageController {
    private final
    MallAuctionMapper mallAuctionMapper;

    private final
    MallAuctionItemMapper mallAuctionItemMapper;

    private final
    MallAuctionItemDetailMapper mallAuctionItemDetailMapper;

    private final
    MallAuctionApplyMapper mallAuctionApplyMapper;

    @Autowired
    public AuctionManageController(MallAuctionMapper mallAuctionMapper, MallAuctionItemMapper mallAuctionItemMapper, MallAuctionItemDetailMapper mallAuctionItemDetailMapper, MallAuctionApplyMapper mallAuctionApplyMapper) {
        this.mallAuctionMapper = mallAuctionMapper;
        this.mallAuctionItemMapper = mallAuctionItemMapper;
        this.mallAuctionItemDetailMapper = mallAuctionItemDetailMapper;
        this.mallAuctionApplyMapper = mallAuctionApplyMapper;
    }

    @AuthRequired
    @GetMapping("getAuctionList")
    @ApiOperation(value = "获得竞拍列表")
    public ServerResponse<PageVo<MallAuctionVo>> getAuctionList(Integer status, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                                                @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize) {
        Integer pageStart = pageSize * (pageNum - 1);
        Integer total;
        total = mallAuctionMapper.selectCountByStatus(status);
        List<MallAuctionVo> mallAuctionVoList = mallAuctionMapper.selectByStatus(status, pageStart, pageSize);
        for (MallAuctionVo mallAuctionVo : mallAuctionVoList) {
            List<MallAuctionItemVo> mallAuctionItemList = mallAuctionItemMapper.selectByPackageNo(Long.valueOf(mallAuctionVo.getPackageNo()));
            mallAuctionVo.setAuctionItemList(mallAuctionItemList);
        }
        PageVo<MallAuctionVo> pageVo = new PageVo<>(pageNum, pageSize, total, mallAuctionVoList);
        return ServerResponse.createBySuccess(pageVo);
    }

    @AuthRequired
    @GetMapping("getAuctionItemDetail")
    @ApiOperation(value = "获得竞拍详情")
    public ServerResponse<List<MallAuctionItemDetail>> getAuctionItemDetail(Integer id) {
        List<MallAuctionItemDetail> mallAuctionItemDetails = mallAuctionItemDetailMapper.selectByItemId(id);
        return ServerResponse.createBySuccess(mallAuctionItemDetails);
    }

    @AuthRequired
    @GetMapping("getPackageList")
    @ApiOperation(value = "获得竞拍包列表")
    public ServerResponse<List<DataVo2>> getPackageList() {
        List<DataVo2> list = mallAuctionMapper.selectPackageNameList();
        return ServerResponse.createBySuccess(list);
    }

    @AuthRequired
    @PostMapping("createPackage")
    @ApiOperation(value = "创建竞价包")
    public ServerResponse createPackage(String package_name) {
        MallAuction mallAuction2 = mallAuctionMapper.selectByName(package_name);
        if (mallAuction2 != null) {
            return ServerResponse.createByErrorMessage("已存在同名竞价包");
        }
        MallAuction mallAuction = new MallAuction();
        Long package_no = NumberUtil.createAuctionNo(80);
        mallAuction.setPackageName(package_name);
        mallAuction.setPackageNo(package_no);
        mallAuction.setCreateTime(new Date());
        mallAuction.setStatus(5);
        mallAuctionMapper.insert(mallAuction);
        return ServerResponse.createBySuccess("创建成功");
    }

    @AuthRequired
    @PostMapping("addProductToPackage")
    @ApiOperation(value = "添加产品到竞价包")
    public ServerResponse addProductToPackage(Integer product_id, Integer package_id, String grade) {
        MallAuctionItem mallAuctionItem = mallAuctionItemMapper.selectByProduct(package_id, product_id, grade);
        if (mallAuctionItem != null) {
            return ServerResponse.createByErrorMessage("已添加，请勿重复添加");
        }
        Long package_no = mallAuctionMapper.selectByPrimaryKey(package_id).getPackageNo();
        MallAuctionItem mallAuctionItem1 = new MallAuctionItem();
        mallAuctionItem1.setProductId(product_id);
        mallAuctionItem1.setGrade(grade);
        mallAuctionItem1.setPackageNo(package_no);
        mallAuctionItem1.setQuantity(new BigDecimal(0));
        mallAuctionItemMapper.insert(mallAuctionItem1);
        return ServerResponse.createBySuccess("添加成功");
    }

    @AuthRequired
    @PostMapping("addAuctionDetail")
    @ApiOperation(value = "完善竞价包")
    public ServerResponse<String> addAuctionDetail(@RequestBody List<MallAuctionItemDetail> list, Integer id) {
        BigDecimal quantity = new BigDecimal(0);
        for (MallAuctionItemDetail mallAuctionItemDetail : list) {
            MallAuctionItemDetail mallAuctionItemDetail1 = mallAuctionItemDetailMapper.selectByCode(id, mallAuctionItemDetail.getMaterialCode(), mallAuctionItemDetail.getColor(), mallAuctionItemDetail.getGrade(), mallAuctionItemDetail.getTwisting(), mallAuctionItemDetail.getMachineNo());
            if (mallAuctionItemDetail1 == null) {
                //新数据 添加
                mallAuctionItemDetail.setId(null);
                mallAuctionItemDetail.setAuctionItemId(id);
                mallAuctionItemDetailMapper.insert(mallAuctionItemDetail);
                quantity = quantity.add(mallAuctionItemDetail.getQuantity());
            } else {
                //旧数据 更新
                mallAuctionItemDetail1.setQuantity(mallAuctionItemDetail.getQuantity());
                mallAuctionItemDetail1.setAuctionItemId(id);
                mallAuctionItemDetailMapper.updateByPrimaryKey(mallAuctionItemDetail1);
                quantity = quantity.add(mallAuctionItemDetail1.getQuantity());
            }
        }
        MallAuctionItem mallAuctionItem = mallAuctionItemMapper.selectByPrimaryKey(id);
        mallAuctionItem.setQuantity(quantity);
        mallAuctionItemMapper.updateByPrimaryKey(mallAuctionItem);
        return ServerResponse.createBySuccess("添加成功");
    }

    @AuthRequired
    @DeleteMapping("deleteAuctionDetail")
    @ApiOperation(value = "删除竞价包详情")
    public ServerResponse<String> deleteAuctionDetail(Integer id) {
        mallAuctionItemDetailMapper.deleteByPrimaryKey(id);
        return ServerResponse.createBySuccess("删除成功");
    }

    @AuthRequired
    @PostMapping("submitAuction")
    @ApiOperation(value = "提交竞价包")
    public ServerResponse submitAuction(String package_name, String start_time, String end_time, BigDecimal lowest_price, BigDecimal start_price, Integer user_id, BigDecimal margin) throws ParseException {
        MallAuction mallAuction = mallAuctionMapper.selectByName(package_name);
        List<MallAuctionItemVo> mallAuctionItemList = mallAuctionItemMapper.selectByPackageNo(mallAuction.getPackageNo());
        for (MallAuctionItemVo mallAuctionItem : mallAuctionItemList) {
            List<MallAuctionItemDetail> list = mallAuctionItemDetailMapper.selectByItemId(mallAuctionItem.getId());
            if (list.size() == 0) {
                return ServerResponse.createByErrorMessage(mallAuctionItem.getName() + "产品未选择物料编码");
            }
        }
        //时间转换
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date StartTime = null;
        Date EndTime = null;
        if (start_time != null && !start_time.equals("") && end_time != null && !end_time.equals("")) {
            StartTime = sdf.parse(start_time);
            EndTime = sdf.parse(end_time);
        }
        mallAuction.setStartTime(StartTime);
        mallAuction.setEndTime(EndTime);
        mallAuction.setStartPrice(start_price);
        mallAuction.setLowestPrice(lowest_price);
        mallAuction.setStatus(0);
        mallAuction.setAuctionCount(0);
        mallAuction.setSubmitUserId(user_id);
        mallAuction.setMargin(margin);
        mallAuctionMapper.updateByPrimaryKey(mallAuction);
        return ServerResponse.createBySuccess("提交成功");
    }

    @AuthRequired
    @GetMapping("getApplyList")
    @ApiOperation(value = "获得竞拍申请列表")
    public ServerResponse getApplyList(Integer status, @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                       @RequestParam(value = "pageSize", defaultValue = "100") Integer pageSize) {
        Integer pageStart = pageSize * (pageNum - 1);
        Integer total;
        total = mallAuctionApplyMapper.selectCountByStatus(status);
        List<MallAuctionApplyVo> list = mallAuctionApplyMapper.selectByStatus(status, pageStart, pageSize);
        Date date = new Date();
        for (MallAuctionApplyVo mallAuctionApplyVo : list) {
            MallAuction mallAuction = mallAuctionMapper.selectByName(mallAuctionApplyVo.getPackageName());
            if (mallAuction == null) {
                return ServerResponse.createByErrorMessage("竞价包不存在");
            }
            if (mallAuction.getStartTime().before(date)) {
                //不能修改
                mallAuctionApplyVo.setCanPass(0);
            } else if (mallAuction.getStartTime().after(date) && mallAuctionApplyVo.getStatus() == 0) {
                mallAuctionApplyVo.setCanPass(1);
            } else {
                mallAuctionApplyVo.setCanPass(0);
            }
        }
        PageVo<MallAuctionApplyVo> pageVo = new PageVo<>(pageNum, pageSize, total, list);
        return ServerResponse.createBySuccess(pageVo);
    }

    @AuthRequired
    @PostMapping("changeApplyStatus")
    @ApiOperation(value = "改变竞拍申请状态")
    public ServerResponse changeApplyStatus(Integer id, String opinion, Integer isPass) {
        MallAuctionApply mallAuctionApply = mallAuctionApplyMapper.selectByPrimaryKey(id);
        if (mallAuctionApply.getStatus() == 1) {
            return ServerResponse.createByErrorMessage("申请状态已变为拒绝，请刷新页面");
        }
        mallAuctionApply.setOpinion(opinion);
        if (isPass == 0) {
            //通过
            Map<String, String> map = new HashMap<>();
            map.put("userId", mallAuctionApply.getUserId().toString());
            map.put("packageNo", mallAuctionApply.getPackageNo().toString());
            map.put("type", "1");
            HttpClientUtil.doGetWithParam("http://47.98.171.71:9094/back/pushAuctionApply", map);
            mallAuctionApply.setStatus(2);
        } else if (isPass == 1) {
            Map<String, String> map = new HashMap<>();
            map.put("userId", mallAuctionApply.getUserId().toString());
            map.put("packageNo", mallAuctionApply.getPackageNo().toString());
            map.put("type", "2");
            HttpClientUtil.doGetWithParam("http://47.98.171.71:9094/back/pushAuctionApply", map);
            mallAuctionApply.setStatus(1);
        } else {
            return ServerResponse.createByErrorMessage("参数错误");
        }
        mallAuctionApplyMapper.updateByPrimaryKey(mallAuctionApply);
        return ServerResponse.createBySuccess("成功");
    }

    @AuthRequired
    @PostMapping("forceChangeApplyStatus")
    @ApiOperation(value = "强制改变竞拍申请状态")
    public ServerResponse forceChangeApplyStatus(Integer id) {
        MallAuctionApply mallAuctionApply = mallAuctionApplyMapper.selectByPrimaryKey(id);
        mallAuctionApply.setStatus(2);
        mallAuctionApplyMapper.updateByPrimaryKey(mallAuctionApply);
        return ServerResponse.createBySuccess("成功");
    }

    @AuthRequired
    @PostMapping("changeAuctionStatus")
    @ApiOperation(value = "改变竞价包状态")
    public ServerResponse<String> changeAuctionStatus(Integer id, Integer status) {
        MallAuction mallAuction = mallAuctionMapper.selectByPrimaryKey(id);
        mallAuction.setStatus(status);
        mallAuctionMapper.updateByPrimaryKey(mallAuction);
        return ServerResponse.createBySuccess("修改成功");
    }

    @AuthRequired
    @DeleteMapping("deleteAuctionItem")
    @ApiOperation(value = "删除竞价包产品")
    public ServerResponse<String> deleteAuctionItem(Integer id) {
        mallAuctionItemMapper.deleteByPrimaryKey(id);
        mallAuctionItemDetailMapper.deleteByItemId(id);
        return ServerResponse.createBySuccess("删除成功");
    }

    @AuthRequired
    @GetMapping("getApplyUserList")
    @ApiOperation(value = "获取申请用户列表")
    public ServerResponse getApplyUserList(Integer id) {
        List<MallAuctionApplyVo> list = mallAuctionApplyMapper.selectByAuctionIdAndStatus(id, 1);
        return ServerResponse.createBySuccess(list);
    }


}
